package com.example.controller;

import com.example.entity.Book;
import com.example.entity.User;
import com.example.service.BookService;
import com.example.service.UserService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.security.Principal;

/**
 * @auth shanyue
 * @date 2025年06月06日15:31
 */
@Controller
@RequestMapping("/books")
public class BookController {

    @Resource
    private BookService bookService;

    @Resource
    private UserService userService;

    // 图书列表页
    @GetMapping
    public String listBooks(Model model, Principal principal) {
        model.addAttribute("username", principal.getName());
        model.addAttribute("books", bookService.listAll());
        return "books";
    }

    // 添加图书表单页
    @GetMapping("/add")
    public String addBookForm() {
        return "admin/book/book_add";
    }

    // 添加图书提交
    @PostMapping("/add")
    public String addBook(Book book) {
        bookService.addBook(book);
        return "redirect:/books";
    }

    // 编辑图书表单页
    @GetMapping("/edit/{id}")
    public String editBookForm(@PathVariable Integer id, Model model) {
        model.addAttribute("book", bookService.getById(id));
        return "admin/book/book_edit";
    }

    // 编辑图书提交
    @PostMapping("/edit")
    public String editBook(Book book) {
        bookService.updateBook(book);
        return "redirect:/books";
    }

    // 删除图书
    @GetMapping("/delete/{id}")
    public String deleteBook(@PathVariable Integer id) {
        bookService.deleteBook(id);
        return "redirect:/books";
    }

    //借阅图书
    @GetMapping("/borrow/{id}")
    public String borrowBook(@PathVariable("id") Integer bookId, Principal principal, RedirectAttributes redirectAttributes) {
        String username = principal.getName();
        User user = userService.findByUsername(username);

        boolean result = bookService.borrowBook(bookId, user.getId());
        if (result) {
            redirectAttributes.addFlashAttribute("message", "借阅成功！");
        } else {
            redirectAttributes.addFlashAttribute("error", "借阅失败，库存不足！");
        }

        return "redirect:/books";
    }

}
